<template>
  <view class="edit-profile-page">
    <view class="profile-form">
      <!-- 头像上传 -->
      <view class="avatar-section">
        <text class="section-title">头像</text>
        <view class="avatar-upload" @click="chooseAvatar">
          <image 
            class="avatar-preview" 
            :src="userForm.avatar || '/static/icons/course-default.png'" 
            mode="aspectFill" 
          />
          <view class="avatar-overlay">
            <text class="upload-text">点击更换</text>
          </view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="label">用户名</text>
          <input 
            class="input" 
            v-model="userForm.username" 
            placeholder="请输入用户名"
            disabled
          />
          <text class="tip">用户名不可修改</text>
        </view>

        <view class="form-item">
          <text class="label">昵称</text>
          <input 
            class="input" 
            v-model="userForm.nickname" 
            placeholder="请输入昵称"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="label">手机号</text>
          <input 
            class="input" 
            v-model="userForm.phone" 
            placeholder="请输入手机号"
            type="number"
            maxlength="11"
          />
        </view>

        <view class="form-item">
          <text class="label">邮箱</text>
          <input 
            class="input" 
            v-model="userForm.email" 
            placeholder="请输入邮箱"
            type="email"
          />
        </view>
      </view>

      <!-- 删除个人简介字段，后端数据库没有相应字段 -->

      <!-- 保存按钮 -->
      <view class="button-section">
        <button 
          class="save-btn" 
          @click="handleSave"
          :loading="saving"
          :disabled="saving"
        >
          保存修改
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { authAPI } from '../../utils/api.js'
import authManager from '../../utils/auth.js'

const saving = ref(false)
const userForm = reactive({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: ''
})

// 获取用户信息 - 使用getUser方法获取完整信息
const loadUserInfo = async () => {
  try {
    // 先尝试调用getUser接口获取完整用户信息
    const result = await authAPI.getUserInfo()
    console.log('getUser接口返回结果:', result)
    
    if (result.code === '00000' && result.data) {
      const userData = result.data
      console.log('从getUser获取的用户数据:', userData)
      
      Object.assign(userForm, {
        username: userData.username || '',
        nickname: userData.nickname || '',
        phone: userData.phone || '',
        email: userData.email || '',
        avatar: getMinioFileUrl(userData.filePath) || userData.avatar || ''
      })
    } else {
      // 如果getUser失败，使用登录时获取的信息作为备用
      const userInfoData = authManager.getUserInfo()
      console.log('使用AuthManager备用信息:', userInfoData)
      
      if (userInfoData) {
        Object.assign(userForm, {
          username: userInfoData.username || '',
          nickname: userInfoData.nickname || '',
          phone: userInfoData.phone || '',
          email: userInfoData.email || '',
          avatar: getMinioFileUrl(userInfoData.filePath) || userInfoData.avatar || ''
        })
      } else {
        // 如果都没有，使用默认值
        Object.assign(userForm, {
          username: authManager.getDisplayName() || '',
          nickname: '',
          phone: '',
          email: '',
          avatar: ''
        })
      }
    }
    
    console.log('设置表单数据:', userForm)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 使用登录时的信息作为备用
    const userInfoData = authManager.getUserInfo()
    if (userInfoData) {
      Object.assign(userForm, {
        username: userInfoData.username || '',
        nickname: userInfoData.nickname || '',
        phone: userInfoData.phone || '',
        email: userInfoData.email || '',
        avatar: getMinioFileUrl(userInfoData.filePath) || userInfoData.avatar || ''
      })
    } else {
      Object.assign(userForm, {
        username: authManager.getDisplayName() || '',
        nickname: '',
        phone: '',
        email: '',
        avatar: ''
      })
    }
    
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    })
  }
}

// 处理MinIO文件URL的函数（参考learn-fronted的实现）
const getMinioFileUrl = (filePath) => {
  if (!filePath) {
    return ''
  }
  
  // 如果已经是完整的URL，直接返回
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath
  }
  
  // 如果是相对路径，拼接MinIO基础URL
  const minioUrl = 'http://172.172.2.99:9000' // 根据您的后端配置调整
  return `${minioUrl}${filePath}`
}

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      // 这里可以上传到服务器，暂时直接使用本地路径
      userForm.avatar = tempFilePath
      
      // 模拟上传到服务器
      uploadAvatar(tempFilePath)
    }
  })
}

// 上传头像
const uploadAvatar = async (filePath) => {
  try {
    uni.showLoading({ title: '上传中...' })
    
    // 这里应该调用上传API，暂时模拟
    setTimeout(() => {
      uni.hideLoading()
      uni.showToast({
        title: '头像上传成功',
        icon: 'success'
      })
    }, 1000)
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '头像上传失败',
      icon: 'none'
    })
  }
}

// 保存用户信息
const handleSave = async () => {
  if (saving.value) return
  
  // 表单验证
  if (!userForm.nickname.trim()) {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none'
    })
    return
  }
  
  if (userForm.phone && !/^1[3-9]\d{9}$/.test(userForm.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  
  if (userForm.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userForm.email)) {
    uni.showToast({
      title: '请输入正确的邮箱',
      icon: 'none'
    })
    return
  }
  
  saving.value = true
  
  try {
    // 获取当前用户ID
    const userId = authManager.getUserId()
    console.log('更新用户信息，用户ID:', userId)
    
    const result = await authAPI.updateUserInfo({
      userId: userId, // 添加用户ID
      nickname: userForm.nickname,
      phone: userForm.phone,
      email: userForm.email,
      avatar: userForm.avatar
    })
    
    if (result.code === '00000') {
      // 使用认证管理器更新用户信息
      authManager.updateUserInfo({
        nickname: userForm.nickname,
        avatar: userForm.avatar,
        email: userForm.email,
        phone: userForm.phone
      })
      
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })
      
      // 通知ProfilePage刷新
      uni.$emit('loginStatusChanged')
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: result.msg || '保存失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  } finally {
    saving.value = false
  }
}

onMounted(async () => {
  await loadUserInfo()
})
</script>

<style scoped>
.edit-profile-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.profile-form {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.avatar-section {
  text-align: center;
  margin-bottom: 60rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

.avatar-upload {
  position: relative;
  display: inline-block;
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  overflow: hidden;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  border-radius: 60rpx;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-upload:active .avatar-overlay {
  opacity: 1;
}

.upload-text {
  color: #fff;
  font-size: 24rpx;
}

.form-section {
  margin-bottom: 60rpx;
}

.form-item {
  margin-bottom: 40rpx;
  position: relative;
}

.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background: #fff;
}

.input:disabled {
  background: #f5f5f5;
  color: #999;
}

.tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  display: block;
}

/* 删除个人简介相关的CSS样式 */

.button-section {
  margin-top: 80rpx;
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: #ff6b35;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.save-btn:disabled {
  background: #ccc;
}
</style>
